/**
 * <p>Title: ServiceZMCMG1.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤 二级库存台账
 * @version 1.0
 * <pre>History:
 *          2010-12-17 下午01:33:45  张坤  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cm.domain.ZMCM2levelbaseaccount;

/**二级库存台账
 * <p>Title: ServiceZMCMG1.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张坤
 * @version 1.0
 * <pre>History:
 *          2010-12-17 下午01:33:45  张坤  Create
 *</pre>
 */
public class ServiceZMCMG1 extends ServiceEPBase {
	/**
	 * 页面初始化方法
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMG1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:35:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) 
	{
		EiInfo outInfo;
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		outInfo = this.query(inInfo);
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		return outInfo;
	}
	
	/**
	 * 查询方法
	 * 根据查询条件查询从表数据信息
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMG1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:36:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) 
	{
		String fdDepotCode = inInfo.getString("fdDepotCode");
		StaticTools.setQueryParameters(inInfo, "fdDepotCode", fdDepotCode, true);//添加查询条件 库房编号
		EiInfo outInfo = super.query(inInfo, "ZMCM2levelbaseaccount.query", new ZMCM2levelbaseaccount());
		
		outInfo.addBlock(getDepartmentWithDepotCode(fdDepotCode));
		return outInfo;
	}
	
	/**
	 * 新增方法
	 * 新增从表数据
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMG1</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:38:45  张坤  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		boolean validateValue = validate(inInfo, "ZMCM2levelmaterialbase.validateexist", new HashMap<String, String>());//判断当前物资在库存中是否有数据
		boolean validatemaxNum = selectMaxNum(inInfo);//判断出库数量是否大于当前库存数量
		EiInfo outInfoinsert;
		
		if(validatemaxNum) {
			return inInfo;
		}
		else
		{	//新增库存台账
			inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_2LEVELBASEACCOUNT"));//主键
			outInfoinsert = super.insert(inInfo, "ZMCM2levelbaseaccount.insert", "result");
			//二级库存信息
			if(validateValue) {//当前库房中该物资信息存在，进行更新库存信息数据
				String fdType = inInfo.getBlock("result").getCellStr(0, "fdType");//判断出库还是入库
				String fdkeyId = selectKeyId(inInfo,"ZMCM2levelmaterialbase.validatekeyid");//主键
				inInfo.getBlock("result").setCell(0, "fdKeyId", fdkeyId);
				if(fdType.trim() == "入库" || fdType.trim().equals("入库"))
				{
					Double fdNum=Double.valueOf(inInfo.getBlock("result").getCellStr(0, "fdNum"));
					inInfo.getBlock("result").setCell(0, "fdNum", fdNum);
					super.update(inInfo, "ZMCM2levelmaterialbase.updatedetail");
				}
				else if(fdType.trim() == "出库" || fdType.trim().equals("出库"))
				{
					Double fdNum=Double.valueOf("-"+inInfo.getBlock("result").getCellStr(0, "fdNum"));
					inInfo.getBlock("result").setCell(0, "fdNum", fdNum);
					super.update(inInfo, "ZMCM2levelmaterialbase.updatedetail");
				}
			}
			else{
				//当前库房中该物资信息不存在，进行新增库存信息数据
				inInfo.getBlock("result").setCell(0, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_2LEVELBASEACCOUNT"));//主键
				outInfoinsert = super.insert(inInfo, "ZMCM2levelmaterialbase.insert", "result");
			}

		return outInfoinsert;
		}
	}
	
	/**
	 * 在新增、修改操作时校验物资编码，名称不能重复
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		
		String fdMaterialId=inInfo.getBlock("result").getCellStr(0, "fdMaterialId");
		String fdDepotCode=inInfo.getBlock("result").getCellStr(0, "fdDepotCode");

		params.put("fdMaterialId", fdMaterialId);//物资ID
		params.put("fdDepotCode", fdDepotCode);//库房编码

		List<?> result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setMsg("当前库存中已经存在该条信息，更新其数据！");
			return true;
		}
		return false;
	}
	/**
	 * 查询主键
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private String selectKeyId(EiInfo inInfo, String sqlName) {
		
		Map<String, String> params = new HashMap<String, String>();
		String fdMaterialId=inInfo.getBlock("result").getCellStr(0, "fdMaterialId");
		String fdDepotCode=inInfo.getBlock("result").getCellStr(0, "fdDepotCode");
		String backKeyId = " ";

		params.put("fdMaterialId", fdMaterialId);//物资ID
		params.put("fdDepotCode", fdDepotCode);//库房编码
		
		List<?> result = dao.query(sqlName, params);
		if(result.size() > 0) {
			Map _map = (Map)result.get(0);
			backKeyId = _map.get("fdKeyId").toString();
		}

		return backKeyId;
	}
	
	/**
	 * 查询可以出库的当前物料数量
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private boolean selectMaxNum(EiInfo inInfo) {
		
		
		String fdMaterialId=inInfo.getBlock("result").getCellStr(0, "fdMaterialId");
		String fdDepotCode=inInfo.getBlock("result").getCellStr(0, "fdDepotCode");
		Double fdMaxNum = new Double(0);
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdMaterialId", fdMaterialId);//物资ID
		params.put("fdDepotCode", fdDepotCode);//库房编码
		
		List<Map> result = dao.query("ZMCM2levelmaterialbase.validateNum", params);
		String fdType = inInfo.getBlock("result").getCellStr(0, "fdType");//判断出库还是入库
		
		if(fdType.trim() == "出库" || fdType.trim().equals("出库"))
		{	
			fdMaxNum = Double.valueOf(result.get(0).get("fdNum").toString());//获取最大可出库值
			Double fdNum  = Double.valueOf(inInfo.getBlock("result").getCellStr(0, "fdNum"));//获取当前输入的数值
			if(fdNum > fdMaxNum)
			{
				String fdMetric = result.get(0).get("fdMetric").toString();//单位
				inInfo.setStatus(-1);
				inInfo.setMsg("出库数量过大，当前库存为："+fdMaxNum+getBlockDisplayByValue("cmes.cs.units",fdMetric)+"！");
				return true;
			}
			return false;
		}
		return false;
	}
	/**
	 * 查询可以出库的当前物料数量
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-17 下午01:33:45  张坤  Create
	 * </p>
	 *
	 */
//	private Double selectMaxCount(EiInfo inInfo) {
//		
//		String fdMaterialId=inInfo.getBlock("result").getCellStr(0, "fdMaterialId");
//		String fdDepotCode=inInfo.getBlock("result").getCellStr(0, "fdDepotCode");
//		Double fdMaxNum = new Double(0);
//		
//		Map<String, String> params = new HashMap<String, String>();
//		params.put("fdMaterialId", fdMaterialId);//物资ID
//		params.put("fdDepotCode", fdDepotCode);//库房编码
//		
//		List<Map> result = dao.query("ZMCM2levelmaterialbase.validateNum", params);
//		fdMaxNum = Double.valueOf(result.get(0).get("fdNum").toString());//获取最大可出库值
//		return fdMaxNum;
//
//	}
	
	/**
	 * 	作废
	 * <p>Function: Approve</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2010-12-25下午04:51:27 张坤
	 * </p>
	 *
	 */
	public EiInfo Invalid(EiInfo inInfo) {
		
		EiInfo _temp = super.update(inInfo, "ZMCM2levelbaseaccount.updateInvalid");
        EiInfo outInfo = this.query(inInfo);
        outInfo.setMsg(_temp.getMsg());
        outInfo.setDetailMsg(_temp.getDetailMsg());
        
        String fdkeyId = selectKeyId(inInfo,"ZMCM2levelmaterialbase.validatekeyid");//主键
        inInfo.getBlock("result").setCell(0, "fdKeyId", fdkeyId);
        String fdType = inInfo.getBlock("result").getCell(0,"fdType").toString();//状态：出库，入库
        Double fdNum = Double.valueOf(inInfo.getBlock("result").getCell(0,"fdNum").toString());//数量
        
		if(fdType.trim() == "入库" || fdType.trim().equals("入库"))
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("二级库入库不能作废！");
			return inInfo;
		}

		inInfo.getBlock("result").setCell(0, "fdNum", fdNum);
		super.update(inInfo, "ZMCM2levelmaterialbase.updateInvalid");

		return outInfo;
	}
	
	/**
	 * 	根据计量单位block的value获得display
	 * <p>Function: getBlockDisplayByValue</p>
	 * <p>Description: </p>
	 * <p>return String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-09-28下午03:33:27 高强
	 * </p>
	 *
	 */
	
	public String getBlockDisplayByValue(String blockName,String id)
	{
		String str ="";
		EiBlock block = InitialData.getInstance().getEiBlockByNo(blockName);
		for(int i=0; i<block.getRowCount();i++)
		{
			if(block.getRow(i).get("value").equals(id))
			{
				return block.getRow(i).get("display").toString();
			}
		}
		return str;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiBlock getDepartmentWithDepotCode(String depotCode) 
	{
		EiBlock block = new EiBlock("cmes.cm.department");

		EiColumn eiColumn = new EiColumn("orgCode");
		eiColumn.setType("C");
		block.addMeta(eiColumn);

		eiColumn = new EiColumn("orgName");
		eiColumn.setType("C");
		block.addMeta(eiColumn);

		Map inMap = new HashMap();
		inMap.put("fdDepotCode", depotCode);
		
		block.setRows(dao.query("ZMCMDepotorganizationInfo.queryDepartment", inMap));
		return block;
	}
}
